document.addEventListener('DOMContentLoaded', () => {
    // 文字配置
    let textConfig = {
        text: '',
        renderMode: 'fireworks', // 'fireworks' 或 'traditional'
        fireworksOptions: {
            particleDensity: 5 // 1-10
        },
        traditionalOptions: {
            color: '#FFFFFF',
            size: 50 // px
        },
        isActive: false
    };
    // 获取Canvas元素
    const canvas = document.getElementById('fireworks');
    const ctx = canvas.getContext('2d');

    // 设置Canvas大小为窗口大小
    canvas.width = window.innerWidth;
    canvas.height = window.innerHeight;

    // 烟花粒子数组
    let particles = [];
    // 烟花火箭数组
    let rockets = [];
    // 上次添加火箭的时间
    let lastRocket = Date.now();
    // 重力
    const gravity = 0.2;
    // 烟花发射频率（毫秒）
    let rocketFrequency = 700;

    // 颜色数组
    const colors = [
        '#FF5252', '#FF4081', '#E040FB', '#7C4DFF', '#536DFE',
        '#448AFF', '#40C4FF', '#18FFFF', '#64FFDA', '#69F0AE',
        '#B2FF59', '#EEFF41', '#FFFF00', '#FFD740', '#FFAB40',
        '#FF6E40'
    ];
    
    // 文字粒子数组
    let textParticles = [];

    // 创建星星背景
    const stars = [];
    for (let i = 0; i < 100; i++) {
        stars.push({
            x: Math.random() * canvas.width,
            y: Math.random() * canvas.height,
            radius: Math.random() * 1.5,
            alpha: Math.random(),
            direction: Math.random() > 0.5 ? 0.005 : -0.005
        });
    }

    // 粒子类
    class Particle {
        constructor(x, y, color) {
            this.x = x;
            this.y = y;
            this.color = color;
            this.alpha = 1;
            this.size = Math.random() * 3 + 1;
            
            // 随机速度和方向
            const angle = Math.random() * Math.PI * 2;
            const speed = Math.random() * 6 + 2;
            this.vx = Math.cos(angle) * speed;
            this.vy = Math.sin(angle) * speed;
            
            // 粒子生命周期
            this.lifetime = Math.random() * 30 + 50;
            this.age = 0;
            
            // 粒子闪烁效果
            this.flicker = Math.random() < 0.5;
            this.flickerRate = Math.random() * 0.2 + 0.1;
        }

        update() {
            // 更新位置
            this.x += this.vx;
            this.y += this.vy;
            
            // 应用重力
            this.vy += gravity;
            
            // 减小速度（空气阻力）
            this.vx *= 0.98;
            this.vy *= 0.98;
            
            // 粒子逐渐变小和透明
            this.size *= 0.96;
            this.alpha = (this.lifetime - this.age) / this.lifetime;
            
            // 闪烁效果
            if (this.flicker) {
                this.alpha *= Math.sin(this.age * this.flickerRate) * 0.5 + 0.5;
            }
            
            // 增加年龄
            this.age++;
            
            // 返回粒子是否存活
            return this.age < this.lifetime && this.alpha > 0.01 && this.size > 0.1;
        }

        draw() {
            ctx.globalAlpha = this.alpha;
            ctx.fillStyle = this.color;
            ctx.beginPath();
            ctx.arc(this.x, this.y, this.size, 0, Math.PI * 2);
            ctx.fill();
            ctx.globalAlpha = 1;
        }
    }

    // 火箭类
    class Rocket {
        constructor() {
            // 从底部随机位置发射
            this.x = Math.random() * canvas.width;
            this.y = canvas.height;
            
            // 目标高度
            const targetHeight = Math.random() * (canvas.height * 0.5) + canvas.height * 0.2;
            
            // 计算速度
            const angle = Math.PI / 2; // 向上发射
            const speed = 8 + Math.random() * 6;
            this.vx = Math.cos(angle) * speed * (Math.random() - 0.5);
            this.vy = -Math.sin(angle) * speed;
            
            // 火箭尾迹粒子
            this.trailParticles = [];
            
            // 火箭颜色
            this.color = colors[Math.floor(Math.random() * colors.length)];
            
            // 火箭大小
            this.size = 2;
            
            // 目标高度
            this.targetY = targetHeight;
            
            // 是否已爆炸
            this.exploded = false;
        }

        update() {
            if (this.exploded) return false;
            
            // 更新位置
            this.x += this.vx;
            this.y += this.vy;
            
            // 应用重力
            this.vy += gravity * 0.1;
            
            // 创建尾迹粒子
            if (Math.random() < 0.5) {
                this.trailParticles.push(new Particle(
                    this.x, 
                    this.y, 
                    this.color
                ));
            }
            
            // 更新尾迹粒子
            for (let i = this.trailParticles.length - 1; i >= 0; i--) {
                if (!this.trailParticles[i].update()) {
                    this.trailParticles.splice(i, 1);
                }
            }
            
            // 检查是否到达最高点或速度变为向下
            if (this.y <= this.targetY || this.vy >= 0) {
                this.explode();
                return false;
            }
            
            return true;
        }

        draw() {
            // 绘制火箭
            ctx.fillStyle = this.color;
            ctx.beginPath();
            ctx.arc(this.x, this.y, this.size, 0, Math.PI * 2);
            ctx.fill();
            
            // 绘制尾迹粒子
            for (const particle of this.trailParticles) {
                particle.draw();
            }
        }

        explode() {
            // 标记为已爆炸
            this.exploded = true;
            
            // 爆炸粒子数量
            const particleCount = 80 + Math.floor(Math.random() * 50);
            
            // 创建爆炸粒子
            for (let i = 0; i < particleCount; i++) {
                particles.push(new Particle(
                    this.x, 
                    this.y, 
                    this.color
                ));
            }
            
            // 随机添加一些不同颜色的粒子
            const secondaryColor = colors[Math.floor(Math.random() * colors.length)];
            for (let i = 0; i < particleCount / 3; i++) {
                particles.push(new Particle(
                    this.x, 
                    this.y, 
                    secondaryColor
                ));
            }
        }
    }

    // 绘制星星背景
    function drawStars() {
        ctx.fillStyle = '#FFFFFF';
        for (const star of stars) {
            ctx.globalAlpha = star.alpha;
            ctx.beginPath();
            ctx.arc(star.x, star.y, star.radius, 0, Math.PI * 2);
            ctx.fill();
            
            // 星星闪烁效果
            star.alpha += star.direction;
            if (star.alpha <= 0.1 || star.alpha >= 0.9) {
                star.direction *= -1;
            }
        }
        ctx.globalAlpha = 1;
    }

    // 添加新火箭
    function addRocket() {
        const now = Date.now();
        // 使用设置的频率控制发射间隔
        // 频率越高（值越小），发射间隔越短；频率越低（值越大），发射间隔越长
        if (now - lastRocket > (Math.random() * 300 + rocketFrequency)) {
            rockets.push(new Rocket());
            lastRocket = now;
        }
    }

    // 点击添加火箭
    canvas.addEventListener('click', (e) => {
        const rocket = new Rocket();
        // 设置火箭位置为点击位置的下方
        rocket.x = e.clientX;
        rocket.y = canvas.height;
        // 设置目标为点击位置
        rocket.targetY = e.clientY;
        // 调整速度以到达目标
        const angle = Math.atan2(canvas.height - e.clientY, e.clientX - rocket.x);
        const speed = 8 + Math.random() * 6;
        rocket.vx = Math.cos(angle) * speed;
        rocket.vy = -Math.sin(angle) * speed;
        
        rockets.push(rocket);
    });

    // 窗口大小改变时调整Canvas大小
    window.addEventListener('resize', () => {
        canvas.width = window.innerWidth;
        canvas.height = window.innerHeight;
    });

    // 频率控制滑块
    const frequencySlider = document.getElementById('frequency-slider');
    const frequencyValue = document.getElementById('frequency-value');

    // 更新频率显示文本
    function updateFrequencyText(value) {
        if (value <= 300) {
            return '极高';
        } else if (value <= 600) {
            return '高';
        } else if (value <= 900) {
            return '中等';
        } else if (value <= 1500) {
            return '低';
        } else {
            return '极低';
        }
    }

    // 初始化频率显示
    frequencyValue.textContent = updateFrequencyText(frequencySlider.value);

    // 监听滑块变化
    frequencySlider.addEventListener('input', (e) => {
        rocketFrequency = parseInt(e.target.value);
        frequencyValue.textContent = updateFrequencyText(rocketFrequency);
    });

    // 文字粒子类
    class TextParticle extends Particle {
        constructor(x, y, color, targetX, targetY) {
            super(x, y, color);
            this.targetX = targetX;
            this.targetY = targetY;
            this.initialX = x;
            this.initialY = y;
            this.easing = 0.05 + Math.random() * 0.05;
            this.arrived = false;
            this.arrivalTime = 0;
            this.stayDuration = 100 + Math.random() * 50;
            this.size = 2 + Math.random() * 1;
        }

        update() {
            if (!this.arrived) {
                // 移动到目标位置
                const dx = this.targetX - this.x;
                const dy = this.targetY - this.y;
                const distance = Math.sqrt(dx * dx + dy * dy);
                
                if (distance < 1) {
                    this.arrived = true;
                    this.arrivalTime = this.age;
                } else {
                    this.x += dx * this.easing;
                    this.y += dy * this.easing;
                }
                
                // 闪烁效果
                if (this.flicker) {
                    this.alpha = Math.sin(this.age * this.flickerRate) * 0.3 + 0.7;
                }
                
                this.age++;
                return true;
            } else {
                // 已到达目标位置，停留一段时间后消失
                const stayTime = this.age - this.arrivalTime;
                
                if (stayTime > this.stayDuration) {
                    this.alpha *= 0.9;
                    this.size *= 0.95;
                }
                
                this.age++;
                return this.alpha > 0.01 && this.size > 0.1;
            }
        }
    }

    // 将文字转换为粒子点阵
    function textToParticles(text, density = 5) {
        const fontSize = 100; // 用于生成点阵的字体大小
        const fontFamily = 'Arial';
        
        // 创建离屏Canvas来渲染文字
        const offscreenCanvas = document.createElement('canvas');
        const offscreenCtx = offscreenCanvas.getContext('2d');
        
        // 设置Canvas大小
        offscreenCtx.font = `bold ${fontSize}px ${fontFamily}`;
        const metrics = offscreenCtx.measureText(text);
        const textWidth = metrics.width;
        const textHeight = fontSize * 1.2; // 近似高度
        
        offscreenCanvas.width = textWidth;
        offscreenCanvas.height = textHeight;
        
        // 绘制文字
        offscreenCtx.font = `bold ${fontSize}px ${fontFamily}`;
        offscreenCtx.fillStyle = '#FFFFFF';
        offscreenCtx.textBaseline = 'top';
        offscreenCtx.fillText(text, 0, 0);
        
        // 获取像素数据
        const imageData = offscreenCtx.getImageData(0, 0, offscreenCanvas.width, offscreenCanvas.height);
        const pixels = imageData.data;
        
        // 采样步长（密度控制）
        const step = Math.max(1, Math.floor(11 - density));
        
        // 粒子点坐标数组
        const points = [];
        
        // 采样像素生成粒子点
        for (let y = 0; y < offscreenCanvas.height; y += step) {
            for (let x = 0; x < offscreenCanvas.width; x += step) {
                const i = (y * offscreenCanvas.width + x) * 4;
                // 检查像素是否不透明
                if (pixels[i + 3] > 128) {
                    points.push({
                        x: x / offscreenCanvas.width,
                        y: y / offscreenCanvas.height
                    });
                }
            }
        }
        
        return {
            points,
            width: textWidth,
            height: textHeight
        };
    }

    // 创建文字烟花
    function createTextFireworks() {
        if (!textConfig.text) return;
        
        // 清除现有的文字粒子
        textParticles = [];
        
        // 获取文字点阵
        const textData = textToParticles(textConfig.text, textConfig.fireworksOptions.particleDensity);
        
        // 计算文字在屏幕中央的位置
        const centerX = canvas.width / 2;
        const centerY = canvas.height / 2;
        const textX = centerX - textData.width / 2;
        const textY = centerY - textData.height / 2;
        
        // 为每个点创建粒子
        const color = colors[Math.floor(Math.random() * colors.length)];
        
        textData.points.forEach(point => {
            // 计算粒子目标位置
            const targetX = textX + point.x * textData.width;
            const targetY = textY + point.y * textData.height;
            
            // 创建从屏幕边缘飞向目标位置的粒子
            const startX = Math.random() * canvas.width;
            const startY = canvas.height + 10;
            
            textParticles.push(new TextParticle(
                startX,
                startY,
                color,
                targetX,
                targetY
            ));
        });
    }

    // 绘制传统文字
    function drawTraditionalText() {
        if (!textConfig.text || !textConfig.isActive) return;
        
        const centerX = canvas.width / 2;
        const centerY = canvas.height / 2;
        
        ctx.font = `bold ${textConfig.traditionalOptions.size}px Arial`;
        ctx.fillStyle = textConfig.traditionalOptions.color;
        ctx.textAlign = 'center';
        ctx.textBaseline = 'middle';
        
        // 添加发光效果
        ctx.shadowColor = textConfig.traditionalOptions.color;
        ctx.shadowBlur = 10;
        
        ctx.fillText(textConfig.text, centerX, centerY);
        
        // 重置阴影
        ctx.shadowBlur = 0;
    }

    // 动画循环
    function animate() {
        // 清除画布
        ctx.fillStyle = 'rgba(0, 0, 0, 0.2)';
        ctx.fillRect(0, 0, canvas.width, canvas.height);
        
        // 绘制星星
        drawStars();
        
        // 添加新火箭
        addRocket();
        
        // 更新和绘制火箭
        for (let i = rockets.length - 1; i >= 0; i--) {
            if (!rockets[i].update()) {
                rockets.splice(i, 1);
            } else {
                rockets[i].draw();
            }
        }
        
        // 更新和绘制粒子
        for (let i = particles.length - 1; i >= 0; i--) {
            if (!particles[i].update()) {
                particles.splice(i, 1);
            } else {
                particles[i].draw();
            }
        }
        
        // 更新和绘制文字粒子
        for (let i = textParticles.length - 1; i >= 0; i--) {
            if (!textParticles[i].update()) {
                textParticles.splice(i, 1);
            } else {
                textParticles[i].draw();
            }
        }
        
        // 绘制传统文字
        if (textConfig.renderMode === 'traditional' && textConfig.isActive) {
            drawTraditionalText();
        }
        
        // 继续动画循环
        requestAnimationFrame(animate);
    }

    // 启动动画
    animate();
    
    // 文字配置界面交互
    const customTextInput = document.getElementById('custom-text');
    const renderModeSelect = document.getElementById('render-mode');
    const fireworksOptions = document.getElementById('fireworks-options');
    const traditionalOptions = document.getElementById('traditional-options');
    const particleDensitySlider = document.getElementById('particle-density');
    const densityValue = document.getElementById('density-value');
    const textColorInput = document.getElementById('text-color');
    const textSizeSlider = document.getElementById('text-size');
    const sizeValue = document.getElementById('size-value');
    const showTextBtn = document.getElementById('show-text-btn');
    
    // 更新粒子密度显示
    function updateDensityText(value) {
        if (value <= 2) {
            return '极低';
        } else if (value <= 4) {
            return '低';
        } else if (value <= 6) {
            return '中等';
        } else if (value <= 8) {
            return '高';
        } else {
            return '极高';
        }
    }
    
    // 初始化粒子密度显示
    densityValue.textContent = updateDensityText(particleDensitySlider.value);
    
    // 监听粒子密度滑块变化
    particleDensitySlider.addEventListener('input', (e) => {
        const value = parseInt(e.target.value);
        textConfig.fireworksOptions.particleDensity = value;
        densityValue.textContent = updateDensityText(value);
    });
    
    // 初始化文字大小显示
    sizeValue.textContent = `${textSizeSlider.value}px`;
    
    // 监听文字大小滑块变化
    textSizeSlider.addEventListener('input', (e) => {
        const value = parseInt(e.target.value);
        textConfig.traditionalOptions.size = value;
        sizeValue.textContent = `${value}px`;
    });
    
    // 监听文字颜色变化
    textColorInput.addEventListener('input', (e) => {
        textConfig.traditionalOptions.color = e.target.value;
    });
    
    // 监听渲染模式变化
    renderModeSelect.addEventListener('change', () => {
        textConfig.renderMode = renderModeSelect.value;
        
        // 显示/隐藏相应的选项
        if (textConfig.renderMode === 'fireworks') {
            fireworksOptions.style.display = 'flex';
            traditionalOptions.style.display = 'none';
        } else {
            fireworksOptions.style.display = 'none';
            traditionalOptions.style.display = 'flex';
        }
    });
    
    // 显示文字按钮点击事件
    showTextBtn.addEventListener('click', () => {
        textConfig.text = customTextInput.value.trim();
        
        if (!textConfig.text) {
            alert('请输入文字内容');
            return;
        }
        
        textConfig.isActive = true;
        
        if (textConfig.renderMode === 'fireworks') {
            createTextFireworks();
        }
    });
});

